import axios from 'axios'
import qs from 'qs'
import cookies from 'js-cookie'
import {Message, Loading} from 'element-ui'
import router from '../router'
import _ from 'lodash'

// 全局配置
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.withCredentials = true;

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 发送请求前
    // 1. 请求令牌校验
    let token = cookies.get('token');
    if (token) {
      config.headers['Authorization'] = token
    } else if (!config.url.includes('/public/')) {
      // 重定向到登录界面
      router.push({path: '/login'});
    }
    // 2. get请求加上时间戳
    if (config.method === 'get') {
      config.params['_t'] = new Date().getTime();
      config.paramsSerializer = (params) => qs.stringify(params);
    }
    // 3. 自动显示加载效果
    if (config.autoLoading !== false) {
      showLoading();
    }

    return config;
  },
  error => {
    // 发生请求错误
    showError('请求发生异常');
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.config.autoLoading !== false) {
      hiddenLoading();
    }
    let data = response.data;
    // 响应正常
    if (data.code === '0') {
      return data.data;
    }
    // 异常响应
    showError(data.message);
    return Promise.reject(data);
  },
  (error) => {
    // 系统异常，直接关闭加载效果
    if (error.config.autoLoading !== false) {
      mergeRequestCount = 0;
      closeLoading();
    }

    showError('系统繁忙，请稍后再试...');
    return Promise.reject(error);
  }
);

function showError(message) {
  Message({
    showClose: true,
    message: message,
    type: 'error'
  });
}

// 合并请求计数器
let mergeRequestCount = 0;

// 遮罩层
let loading;

/**
 * 显示加载效果
 */
function startLoading() {
  loading = Loading.service({
    lock: true
  });
}

/**
 * 关闭加载效果
 */
function closeLoading() {
  if (mergeRequestCount === 0) {
    loading.close();
  }
}

/**
 * 判断是否需要显示加载效果
 */
function showLoading() {
  if (mergeRequestCount === 0) {
    startLoading();
  }
  mergeRequestCount++;
}

/**
 * 判断是否需要关闭加载效果
 */
function hiddenLoading() {
  if (mergeRequestCount === 0) {
    return;
  }
  mergeRequestCount--;
  if (mergeRequestCount === 0) {
    // 延迟100毫秒在关闭
    _.debounce(closeLoading, 100)();
  }
}

export const get = (url, params) => {
  return new Promise((resolve, reject) => {
    axios.get(url, params)
      .then((response) => {
        resolve(response);
        return false;
      })
      .catch((error) => {
        reject(error);
      })
  })
};

export const post = (url, data = {}) => {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then((response) => {
        resolve(response);
        return false;
      })
      .catch((error) => {
        reject(error);
      })
  })
};
